import mongoose from "mongoose";
const db = 'mongodb://localhost/test'
import glob from 'glob'
import { resolve } from 'path'
mongoose.Promise = global.Promise;
export const initSchemas = () => {
    glob.sync(resolve(__dirname, './schema/', '**/*.js')).forEach(require)
}
export const connect = () => {
    let maxConnectTimes = 0;
    return new Promise((resolve,reject) => {

        if(process.env.NODE_ENV !== 'production'){
            // 如果是开发环境就打印日志
            mongoose.set('debug',true)
        }
    
        mongoose.connect(db)
    
        mongoose.connection.on('disconnected',()=>{
            maxConnectTimes ++;
            if(maxConnectTimes < 5){
                mongoose.connect(db)
            } else {
                throw new Error('数据库挂了,快去修复')
            }
        })
    
        mongoose.connection.on('error',err=>{
            maxConnectTimes ++;
            if(maxConnectTimes < 5){
                mongoose.connect(db)
            } else {
                throw new Error('数据库挂了,快去修复')
            }
            reject(err)
        })
    
        mongoose.connection.once('open',() => {
            // const Dog = mongoose.model('Dog',{
            //     name:String
            // });
            // const doga = new Dog({
            //     name:'lokk'
            // })
            // doga.save().then(()=>{
            //     console.log('成功存入了')
            // })
            resolve()
            console.log('MongoDB Connected successfully')
        })

    })
    

}